debug = false;


//TODO addScript function
//TODO add needed scripts

/**
 * Add a Element if it not exist
 * @param id the id of the element (if you not pass id it create the element)
 * @param type the type of the element (example div, input), default div
 */
function addElement(id, type)
{
    if (type == undefined)
    {
        type = 'div';
    }
    var pageDiv = null;
    var newDiv  = null;
    tempDiv     = document.getElementById(id);
    if (!tempDiv)
    {
        newDiv      = document.createElement(type);
        if (id != undefined)
        {
            newDiv.id   = id;
        }
        pageDiv     = document.getElementById("pageDiv");
        document.body.insertBefore(newDiv, pageDiv);
    }
}

function ajaxCall(form, extraData, returnElement, phpFunction, url)
{
    log('ajaxFunction', phpFunction)
    log('ajaxReturnElement', returnElement)
    var data                = $(form).serialize(true);
    if (extraData)
    {
        //TODO manage extraData
    }
    data['ajax']            = true;
    data['phpFunction']     = phpFunction;
    new Ajax.Updater(returnElement, url, {method: 'post',  parameters: data, evalScripts: true} );
}

function ajax(returnElement, phpFunction)
{   
	log('ajax');
	log('returnElement',returnElement);
	log('phpFunction',phpFunction);
    ajaxCall('formSite', null, returnElement, phpFunction, 'index.php');
}

function keyDown(e)
{
    if ( window.event ) // IE
    {
        keyCode = e.keyCode;
    }
    else if ( e.which ) // Netscape/Firefox/Opera
    {
        keyCode = e.which;
    }

    log('KeyCode', keyCode);

    element         = document.activeElement; //take the active element
    elementKey      = element.getAttribute('key');

    log('ActiveElement', element.id);
    log('elementKey', elementKey)

    //if is a submit call submit function of the first form
    if ( element.type == 'submit' || element.tagName == 'BUTTON' )
    {

        log('submit or button');
        return true;
    }

    if ( element && keyCode == elementKey ) //enter
    {
        onPress = element.getAttribute('onPress'); //try to get attribute as case sensitive

        if ( !onPress )
        {
            onPress = element.getAttribute('onpress'); //try to get attribute lowercase
        }

        if ( onPress )
        {
            log('onPress', onPress);
            eval( onPress ); //call the method
        }

        e.preventDefault();
    }
    else
    {

        //prevent the default enter/submit function
        if (keyCode == 13)
        {
            log('enter preventDefault');
            e.preventDefault();
        }
    }
}


/**
 * Make a log if debug is defined
 */
function log(txt, var_)
{
    if ( debug )
    {
        if (var_)
        {
            console.log(txt + '=' + var_ );
        }
        else
        {
            console.log( txt );
        }
    }
}